<template>
  <div>

    <el-card class="duidanone-box-card" shadow="hover">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-position="right">

<!--        <el-form-item label="手牌" prop="handBrand" label-width="50px">
          <el-input
            v-model="queryParams.handBrand"
            clearable
            placeholder=""
          />
        </el-form-item>

        <el-form-item label="消费名称" prop="entryName" label-width="90px">
          <el-input
            v-model="queryParams.entryName"
            clearable
            placeholder=""
          />
        </el-form-item>

        <el-form-item label="助记码" prop="mnemonicCode" label-width="80px">
          <el-input
            v-model="queryParams.mnemonicCode"
            clearable
            placeholder=""
          />
        </el-form-item>

        <el-form-item label="项目类别" prop="" label-width="90px">
          <el-select v-model="queryParams.projectCategory" placeholder="请选择商品类别" clearable style="width: 240px">
            <el-option
              v-for="dict in dict.type.yqg_project_category"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"

            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="同来" prop="together" label-width="60px">
          <el-input
            v-model="queryParams.together"
            clearable
            placeholder=""
          />
        </el-form-item>-->
      </el-form>

      <el-form>
        <el-form-item style="text-align: right;">
<!--          <el-button type="primary"  @click="handleQuery">读 牌</el-button>
          <el-button type="primary" plain @click="resetQuery">重 置</el-button>-->
          <el-button  @click="back" >返 回</el-button>
        </el-form-item>
      </el-form>

    </el-card>


    <el-card class="duidantwo-box-card" shadow="hover">
      <el-tabs v-model="activeName" @tab-click="handleClick">
<!--        <el-tab-pane label="明细模式" name="first">-->
          <div>
            <el-table class="duidanlisttable" empty-text = "玉泉宫" :data="tableData" sticky-header height="644px"
                      border
                      style="width: 100% ;margin-top: 10px;overflow-y: auto;">
              <el-table-column type="index" label="序号" min-width="10%" align="center"></el-table-column>
              <el-table-column prop="projectCode" label="商品编号" min-width="10%" align="center"></el-table-column>
              <el-table-column prop="entryName" label="商品名称" min-width="10%" align="center"></el-table-column>
              <el-table-column prop="mnemonicCode" sortable label="助记码" min-width="10%" align="center"></el-table-column>
              <el-table-column prop="projectCategory" label="项目类别" min-width="6%" align="center">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.yqg_project_category" :value="scope.row.projectCategory"/>
                </template>
              </el-table-column>
              <el-table-column  prop="consumptionStatus" label="商品状态"min-width="6%" align="center">
                <template slot-scope="scope">
                  <el-button v-if="scope.row.consumptionStatus==0" disabled="disabled" style="cursor: unset" type="primary" plain size="mini">正常</el-button>
                  <el-button v-if="scope.row.consumptionStatus==1" disabled="disabled" style="cursor: unset" type="danger" plain size="mini">退单</el-button>
<!--                  <span v-if="scope.row.consumptionStatus==0" class="status">正常</span>
                  <span v-if="scope.row.consumptionStatus==1" class="status1">退单</span>-->
                </template>
              </el-table-column>
              <el-table-column prop="unitPrice" sortable label="单价" min-width="6%" align="center"></el-table-column>
              <el-table-column prop="quantity" sortable label="数量" min-width="6%" align="center"></el-table-column>
              <el-table-column
                prop="totalAmount"
                sortable
                label="金额" min-width="6%" align="center">
              </el-table-column>

              <el-table-column prop="recordingTime" sortable label="录单时间" min-width="15%" align="center"></el-table-column>
              <el-table-column prop="note10" label="备注" min-width="15%" align="center"></el-table-column>
<!--              <el-table-column prop="note" label="备注" align="center"></el-table-column>-->
            </el-table>
            <div style="background: #F8F8F9;width: 100%;height: 46px">
              <el-row>
                <el-col :span="6" ><div style="margin-top: 13px;margin-left: 330px">商品数量：</div></el-col>
                <el-col :span="6"><div style="margin-top: 13px;margin-right: 330px">{{ quantity }}个</div></el-col>
                <el-col :span="6"><div style="margin-top: 13px;margin-left: 330px">合计金额：</div></el-col>
                <el-col :span="6"><div style="margin-top: 13px;margin-right: 330px">{{ amount }}元</div></el-col>
              </el-row>
<!--              <div >商品数量：</div>
              <div>{{ quantity }}</div>
              <span>合计金额：</span>
              <span>{{ amount }}</span>-->

            </div>
            <!--合计行（头）-->
            <!--        <el-table sticky-header border style="width: 100% ;margin-top: -1px;">
                   <el-table-column label="合计" width="100" align="center"></el-table-column>
                   <el-table-column label="" width="180" align="center"></el-table-column>
                   <el-table-column label="" width="300" align="center"></el-table-column>
                   <el-table-column label="" width="140" align="center"></el-table-column>
                   <el-table-column label="" width="140" align="center"></el-table-column>
                   <el-table-column label="" width="140" align="center"></el-table-column>
                   <el-table-column label="" width="180" align="center"></el-table-column>
                   <el-table-column :label="quantity" width="180" align="center"></el-table-column>

                   <el-table-column :label="amount" width="200" align="center"></el-table-column>
                   <el-table-column l width="242" align="center"></el-table-column>

                 <el-table-column label="" align="center"></el-table-column>
                 </el-table>-->

            <!--覆盖层，重要（大概），忽删-->
<!--            <div style="background-color: white;z-index: 99;margin-top: -60px"/>-->

          </div>

<!--        </el-tab-pane>-->
<!--        <el-tab-pane label="合计模式" name="second">合计模式</el-tab-pane>
        <el-tab-pane label="合计模式2" name="third">合计模式2</el-tab-pane>-->

      </el-tabs>
    </el-card>
  </div>


</template>

<script>

import {listDetails,gethands} from "@/api/module/whd/duizhang";

export default {
  dicts: ['yqg_hand_category', 'yqg_hand_state', 'yqg_payment_method', 'yqg_consumption_status', 'yqg_retention_status', 'yqg_project_category', 'yqg_post', 'yqg_check_out_status', 'yqg_department', 'yqg_merge_status', 'yqg_sailings_signs', 'yqg_next_clock_status'],
  data() {

    return {
      // 遮罩层
      loading: true,
      // 查询参数
      // 总条数
      total: 0,
      queryParams: {
        userId: null,
        deptId: null,
        department: null,
        nickName: null,
        userName: null,
        post: null,
        handBrand: "",
        handCategory: null,
        handState: null,
        retentionStatus: null,
        mergeStatus: null,
        openingTime: null,
        drawTime: null,
        mergeHands: null,
        mergeBarBillsId: null,
        leaveTime: null,
        beforeLeave: null,
        beforeBarBillsId: null,
        entryName: null,
        projectCategory: null,
        projectCode: null,
        mnemonicCode: null,
        unit: null,
        unitPrice: null,
        commissionPrice: null,
        together: null,
        sailingsSigns: null,
        barBillsId: null,
        recordingTime: null,
        quantity: null,
        totalAmount: null,
        seat: null,
        orderNumber: null,
        paymentMethod: null,
        consumptionStatus: null,
        chargebackTime: null,
        reasonForChargeback: null,
        chargebackProcessorAccount: null,
        chargebackProcessorName: null,
        clockTime: null,
        nextClockTime: null,
        nextClockStatus: null,
        recordEmployeeNumber: null,
        recorderEmployeeName: null,
        roomType: null,
        openingHours: null,
        checkOutTime: null,
        checkOutStatus: null,
        note1: null,
        note2: null,
        note3: null,
        note4: null,
        note5: null,
        note6: null,
        note7: null,
        note8: null,
        note9: null,
        note10: null
      },
      activeName: 'first',
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      tableData: [],
      // 为适应数据处理新增
      // 处理后的数组
      detailTableData: [],
      // 已点
      ordered: [],
      mergeOrdered: [],
      retentionOrdered: [],
      // 对应索引
      orderedIndex: {},
      // 合计
      amount: 0, // 总价格
      quantity: 0, // 总数量
    }
  },
  created() {
    const ID = this.$route.query.ID;
    this.queryParams.barBillsId=ID.toString();
    if( this.queryParams.barBillsId!==""&& this.queryParams.barBillsId!==null){
      console.log(typeof (this.queryParams.barBillsId ));
      this.getDetailsList();
    }
   /*this.getDetailsList();*/
  },
  methods: {
    //返回方法
    back(){
      this.$router.push({path: '/batai/duizhang'});
    },
    reset() {
      this.form = {
        ID: null,
        userId: null,
        deptId: null,
        department: null,
        nickName: null,
        userName: null,
        post: null,
        handBrand: "",
        handCategory: null,
        handState: null,
        retentionStatus: null,
        mergeStatus: null,
        openingTime: null,
        drawTime: null,
        mergeHands: null,
        mergeBarBillsId: null,
        leaveTime: null,
        beforeLeave: null,
        beforeBarBillsId: null,
        entryName: null,
        projectCategory: null,
        projectCode: null,
        mnemonicCode: null,
        unit: null,
        unitPrice: null,
        commissionPrice: null,
        together: null,
        sailingsSigns: null,
        barBillsId: null,
        recordingTime: null,
        quantity: null,
        totalAmount: null,
        seat: null,
        orderNumber: null,
        paymentMethod: null,
        consumptionStatus: null,
        chargebackTime: null,
        reasonForChargeback: null,
        chargebackProcessorAccount: null,
        chargebackProcessorName: null,
        clockTime: null,
        nextClockTime: null,
        nextClockStatus: null,
        recordEmployeeNumber: null,
        recorderEmployeeName: null,
        roomType: null,
        openingHours: null,
        checkOutTime: null,
        checkOutStatus: null,
        note1: null,
        note2: null,
        note3: null,
        note4: null,
        note5: null,
        note6: null,
        note7: null,
        note8: null,
        note9: null,
        note10: null
      };
      this.resetForm("form");
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.amount = 0
      this.quantity = 0
      this.queryParams.handBrand="";
      this.queryParams.projectCategory = "";
      this.tableData = [];
      this.detailTableData = [];
      this.ordered = [];
    },
    /** 查询消费详细列表 */
    getDetailsList() {

      this.detailTableData = [];
      this.ordered = [];
      console.log("分类"+this.queryParams.projectCategory);
      listDetails(this.queryParams).then(response => {
        this.tableData = response.rows;
        // 手动计算合计
        this.amount = 0
        this.quantity = 0
        for (let i = 0; i < this.tableData.length; i++) {
          if(this.tableData[i].consumptionStatus==="0"){
            this.quantity +=parseInt(this.tableData[i].quantity)
            this.amount +=parseInt(this.tableData[i].totalAmount)
          }

        }

        // 索引
        var index = 0
        // 数据处理，重复进行合并
        for (let i = 0; i < this.tableData.length; i++) {
          // 第一个直接push进数组
          if (i === 0) {
            // 如果是留牌项目
            if (this.tableData[i].retentionStatus === "0") {
              this.detailTableData.push({
                projectCode: this.tableData[i].projectCode,
                entryName: this.tableData[i].entryName,
                projectCategory: this.tableData[i].projectCategory,
                quantity: parseInt(this.tableData[i].quantity),
                unitPrice: this.tableData[i].unitPrice,
                totalAmount: parseFloat(this.tableData[i].totalAmount),
                mnemonicCode: this.tableData[i].mnemonicCode,
                recordingTime: this.tableData[i].recordingTime,
                note: "来自" + this.tableData[i].beforeLeave + "留牌",
              })
              this.retentionOrdered.push({
                name: this.tableData[i].entryName,
                hand: this.tableData[i].beforeLeave,
                index: index
              })
              index += 1
            }
            // 如果是并牌项目
            else if (this.tableData[i].mergeStatus === "0") {
              this.detailTableData.push({
                projectCode: this.tableData[i].projectCode,
                entryName: this.tableData[i].entryName,
                projectCategory: this.tableData[i].projectCategory,
                quantity: parseInt(this.tableData[i].quantity),
                unitPrice: this.tableData[i].unitPrice,
                totalAmount: parseFloat(this.tableData[i].totalAmount),
                mnemonicCode: this.tableData[i].mnemonicCode,
                recordingTime: this.tableData[i].recordingTime,
                note: "来自" + this.tableData[i].handBrand + "并牌",
              })
              this.mergeOrdered.push({
                name: this.tableData[i].entryName,
                hand: this.tableData[i].handBrand,
                index: index
              })
              index += 1
            }
            // 其它（主牌项目）
            else {
              this.detailTableData.push({
                projectCode: this.tableData[i].projectCode,
                entryName: this.tableData[i].entryName,
                projectCategory: this.tableData[i].projectCategory,
                quantity: parseInt(this.tableData[i].quantity),
                unitPrice: this.tableData[i].unitPrice,
                totalAmount: parseFloat(this.tableData[i].totalAmount),
                mnemonicCode: this.tableData[i].mnemonicCode,
                recordingTime: this.tableData[i].recordingTime,
              })
              this.ordered.push(this.tableData[i].entryName)
              this.orderedIndex[this.tableData[i].entryName] = index
              index += 1
            }
          }
          // 不是第一个（可能需要进行数据合并）
          else {
            // 如果是留牌数据
            if (this.tableData[i].retentionStatus === "0") {
              // 如果数组为空，直接插入数据
              if (this.retentionOrdered.length === 0) {
                this.retentionOrdered.push({
                  name: this.tableData[i].entryName,
                  hand: this.tableData[i].beforeLeave,
                  index: index
                })
                index += 1
                this.detailTableData.push({
                  projectCode: this.tableData[i].projectCode,
                  entryName: this.tableData[i].entryName,
                  projectCategory: this.tableData[i].projectCategory,
                  quantity: parseInt(this.tableData[i].quantity),
                  unitPrice: this.tableData[i].unitPrice,
                  totalAmount: parseFloat(this.tableData[i].totalAmount),
                  mnemonicCode: this.tableData[i].mnemonicCode,
                  recordingTime: this.tableData[i].recordingTime,
                  note: "来自" + this.tableData[i].beforeLeave + "留牌",
                })
              }
              // 否则
              else {
                for (let j = 0; j < this.retentionOrdered.length; j++) {
                  // 如果数组中已经存在该项目，且手牌号相同
                  if (this.retentionOrdered[j].name === this.tableData[i].entryName && this.retentionOrdered[j].hand === this.tableData[i].beforeLeave) {
                    // 合并数量和总价
                    this.detailTableData[this.retentionOrdered[j].index].quantity += parseInt(this.tableData[i].quantity)
                    this.detailTableData[this.retentionOrdered[j].index].totalAmount += parseFloat(this.tableData[i].totalAmount)
                    break
                  }
                  // 如果不存在
                  if (j === this.retentionOrdered.length - 1) {
                    this.retentionOrdered.push({
                      name: this.tableData[i].entryName,
                      hand: this.tableData[i].beforeLeave,
                      index: index
                    })
                    index += 1
                    this.detailTableData.push({
                      projectCode: this.tableData[i].projectCode,
                      entryName: this.tableData[i].entryName,
                      projectCategory: this.tableData[i].projectCategory,
                      quantity: parseInt(this.tableData[i].quantity),
                      unitPrice: this.tableData[i].unitPrice,
                      totalAmount: parseFloat(this.tableData[i].totalAmount),
                      mnemonicCode: this.tableData[i].mnemonicCode,
                      recordingTime: this.tableData[i].recordingTime,
                      note: "来自" + this.tableData[i].beforeLeave + "留牌",
                    })
                    j++
                  }
                }
              }
            }
            // 如果是并牌数据
            else if (this.tableData[i].mergeStatus === "0") {
              // 如果数组为空，直接插入数据
              if (this.mergeOrdered.length === 0) {
                this.mergeOrdered.push({
                  name: this.tableData[i].entryName,
                  hand: this.tableData[i].handBrand,
                  index: index
                })
                index += 1
                this.detailTableData.push({
                  projectCode: this.tableData[i].projectCode,
                  entryName: this.tableData[i].entryName,
                  projectCategory: this.tableData[i].projectCategory,
                  quantity: parseInt(this.tableData[i].quantity),
                  unitPrice: this.tableData[i].unitPrice,
                  totalAmount: parseFloat(this.tableData[i].totalAmount),
                  mnemonicCode: this.tableData[i].mnemonicCode,
                  recordingTime: this.tableData[i].recordingTime,
                  note: "来自" + this.tableData[i].handBrand + "并牌",
                })
              }
              // 否则
              else {
                for (let j = 0; j < this.mergeOrdered.length; j++) {
                  // 如果数组中已经存在该项目，且手牌号相同
                  if (this.mergeOrdered[j].name === this.tableData[i].entryName && this.mergeOrdered[j].hand === this.tableData[i].handBrand) {
                    // 合并数量和总价
                    this.detailTableData[this.mergeOrdered[j].index].quantity += parseInt(this.tableData[i].quantity)
                    this.detailTableData[this.mergeOrdered[j].index].totalAmount += parseFloat(this.tableData[i].totalAmount)
                    break
                  }
                  // 如果不存在
                  if (j === this.mergeOrdered.length - 1) {
                    this.mergeOrdered.push({
                      name: this.tableData[i].entryName,
                      hand: this.tableData[i].handBrand,
                      index: index
                    })
                    index += 1
                    this.detailTableData.push({
                      projectCode: this.tableData[i].projectCode,
                      entryName: this.tableData[i].entryName,
                      projectCategory: this.tableData[i].projectCategory,
                      quantity: parseInt(this.tableData[i].quantity),
                      unitPrice: this.tableData[i].unitPrice,
                      totalAmount: parseFloat(this.tableData[i].totalAmount),
                      mnemonicCode: this.tableData[i].mnemonicCode,
                      recordingTime: this.tableData[i].recordingTime,
                      note: "来自" + this.tableData[i].handBrand + "并牌",
                    })
                    j++
                  }
                }
              }
            }
            // 其它（主牌数据）
            else {
              // 如果数组中已经存在该项目
              if (this.ordered.includes(this.tableData[i].entryName)) {
                this.detailTableData[this.orderedIndex[this.tableData[i].entryName]].quantity += parseInt(this.tableData[i].quantity)
                this.detailTableData[this.orderedIndex[this.tableData[i].entryName]].totalAmount += parseFloat(this.tableData[i].totalAmount)
              }
              // 如果不存在
              else {
                this.ordered.push(this.tableData[i].entryName)
                this.orderedIndex[this.tableData[i].entryName] = index
                index += 1
                this.detailTableData.push({
                  projectCode: this.tableData[i].projectCode,
                  entryName: this.tableData[i].entryName,
                  projectCategory: this.tableData[i].projectCategory,
                  quantity: parseInt(this.tableData[i].quantity),
                  unitPrice: this.tableData[i].unitPrice,
                  totalAmount: parseFloat(this.tableData[i].totalAmount),
                  mnemonicCode: this.tableData[i].mnemonicCode,
                  recordingTime: this.tableData[i].recordingTime,
                })
              }
            }
          }
        }
      });
    },
    //手牌号搜索按钮操作
    handleQuery() {

      this.tableData = [];
      this.amount = 0
      this.quantity = 0
      if(!this.queryParams.handBrand.includes(" ")){
        if (this.queryParams.handBrand != null && this.queryParams.handBrand !== "") {
          gethands(this.queryParams.handBrand).then(response=>{
            this.$modal.msgSuccess("读牌成功");
            this.getDetailsList();
          });
          // console.log(this.queryParams.handBrand)

        }else {
          this.$modal.msgError("手牌号为空,请录入手牌");
        }
      }else{
        this.$modal.msgError("手牌号中包含空格,请重新录入");
      }


    },
    //指定列求和
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      //第一列命名合计
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        // console.log(column.property)

        //指定allCompanyNum、allCarNum、allDriverNum不求和，其余列军求和
        if (column.property !== 'visitorId' && column.property !== 'tableNumber' && column.property !== 'entryName' && column.property !== 'projectCategory'
          && column.property !== 'projectCode' && column.property !== 'mnemonicCode' && column.property !== 'unit'
          && column.property !=='unitPrice' && column.property !== 'recordingTime'&& column.property !== 'consumptionStatus') {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index];
        } else {
          sums[index] = ''
        }
      });
      let jine = sums[sums.length - 2];
      sums[sums.length - 2] = Math.round(jine * 100) / 100
      return sums
    },
    onSubmit() {
      // console.log('submit!');
    },
    handleNodeClick(data) {
      // console.log(data);
    },
    handleClick(tab, event) {
      // console.log(tab, event);
    }
  }
}


</script>


<style lang="scss" scoped>

.duidanone-box-card {
  height: 70px;
  margin-left: 10px;
  margin-right: 10px;
  margin-top: 15px;
  margin-bottom: 10px;
}

.duidantwo-box-card {
  height: 735px;
  margin-left: 10px;
  margin-right: 10px;
  margin-top: 15px;
  margin-bottom: 10px;
}

.button {
  width: 145px;
  height: 50px;
}

::-webkit-scrollbar {
  width: 0 !important;
}
::-webkit-scrollbar{
  width: 0!important;height: 0;
}
::v-deep .el-table__body-wrapper {
  // 整个滚动条
  &::-webkit-scrollbar {
    width: 0px; // 纵向滚动条的宽度
    background: rgba(213, 215, 220, 0.3);
    border: none;
  }
  // 滚动条轨道
  &::-webkit-scrollbar-track {
    border: none;
  }
}
// --------------------隐藏table gutter列和内容区右侧的空白 start
::v-deep .duidanlisttable th.gutter {
  display: none;
  width: 0
}
::v-deep .duidanlisttable colgroup col[name='gutter'] {
  display: none;
  width: 0;
}
// 这个样式不加的话内容哪里会缺一点，估计是因为滚动条哪里缺的没有补上
::v-deep .el-table__body {
  width: 100% !important;
}
</style>
